angular.module('starter.services', [])

.factory('Storage', function() {
    return {
        set: function(key, data) {
            return window.localStorage.setItem(key, window.JSON.stringify(data));
        },
        get: function(key) {

            return window.JSON.parse(window.localStorage.getItem(key));
        },
        remove: function(key) {
            return window.localStorage.removeItem(key);
        }
    };
})

/*.factory('WXMaibei', function ($resource, $rootScope, $ionicLoading, ENV) {
    var ApiUrl = ENV.api,service = {};
    var resource = $resource(ApiUrl+'Home/Pay/getOpenid', {}, {
        query:{
            method: 'get',
            params: {
                uid:'@uid',
                url: '@url'
            },
            timeout: 2000
        }
    });

    /!****** 用户微信公众号授权 ******!/
    service.CustomerAuth = function (customer_id, url) {
        var params = {
            uid: customer_id,
            url: url
        };
        resource.query(params, function (r) {
            console.log(r);
            return true;
        });
    }
    return service;
})*/

.factory('BillListFactory', function($rootScope, $resource, $location, $ionicLoading, ENV){
    var ApiUrl = ENV.api,
        service = {},
        offset = 0,
        length = 10,
        res_data = {};
    var resource_ucenter = $resource(ApiUrl, {}, {
        query:{
            method: 'post',
            url: ApiUrl+'Home/UserCenter/getBillList',
            timeout: 2000
        }
    });
    var resource_pay = $resource(ApiUrl, {}, {
        query:{
            method: 'post',
            url: ApiUrl+'Home/Pay/wxpayConfirm',
            timeout: 2000
        }
    });

    /****** 获取银行卡历史信息 ******/
    service.getBillList = function(customer_id){
        var params = {
            customer_id: customer_id,
            offset: offset,
            length: length,
            no_need_sign: true
        };
        resource_ucenter.query(params, function(r){
            if(r.code === undefined){
                return false;
            }
            //成功的回调函数
            if(r.code == 0){
                res_data = r;
            }else{
                $ionicLoading.show({
                    noBackdrop: true,
                    template: r.msg,
                    duration: 1500
                });
                return false;
            }
            //在这里请求完成以后，通知controller
            $rootScope.$broadcast('onBillList');
        })
    };

    /****** 返回前端已经获取到的银行卡历史信息 ******/
    service.returnBillList = function () {
        //返回我们保存的数据
        if(res_data.code === undefined){
            return false;
        }
        return res_data;
    };

    /****** 获取下一页银行卡历史信息 ******/
    service.getMoreBillList = function (customer_id) {
        if(res_data.data === undefined || res_data.data.length == 0){
            return false;
        }
        //获取之前已经获取到的信息
        var old_res_data = res_data.data;
        res_data.offset = parseInt(res_data.offset);
        resource_ucenter.query({
            customer_id: customer_id,
            offset: res_data.offset,
            length: res_data.length,
            no_need_sign: true
        }, function (r) {
            if(r.code === undefined){
                return false;
            }
            if(r.code == 0){
                res_data = r;
                res_data.data = old_res_data.concat(r.data);
            }else{
                $ionicLoading.show({
                    noBackdrop: true,
                    template: r.msg,
                    duration: 1500
                });
                return false;
            }
            //在这里请求完成以后，通知controller
            $rootScope.$broadcast('onBillList');
        })
    };

    service.payOrderByConsumeId = function (bill) {
        var openid = location.href.substr(location.href.indexOf('=')+1)?location.href.substr(location.href.indexOf('=')+1):0;
        if(!openid){
            $ionicLoading.show({
                noBackdrop: true,
                template: "哎呀，系统开小差了",
                duration: 1500
            });
            return false;
        }
        var params = {};
        //次月
        if(bill.repay_type == 1){
            params = {
                customer_id: bill.customer_id,
                paytype: 4,
                openid: openid,
                no_need_sign: true,
                consume_data: [{
                    consume_id: bill.consume_id,
                    type: bill.repay_type,
                    amount: bill.repay_amount,
                    overdue_amount: bill.fine,
                    repay_date: bill.repay_date,
                    installment_history:[]
                }]
            };
        }
        if(bill.repay_type == 2){
            params = {
                customer_id: bill.customer_id,
                paytype: 4,
                openid: openid,
                no_need_sign: true,
                consume_data: [{
                    consume_id: bill.consume_id,
                    type: bill.repay_type,
                    amount: "",
                    overdue_amount: "",
                    repay_date: "",
                    installment_history:[{
                        amount: bill.repay_amount,
                        overdue_amount: bill.fine,
                        repay_date: bill.repay_date,
                    }]
                }]
            };
        }

        resource_pay.query(params, function(r) {
            if (r.code === undefined) {
                return false;
            }
            //成功的回调函数
            if (r.code == 0) {
                function onBridgeReady(){
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId":r.data.appId,
                            "timeStamp":r.data.timeStamp,
                            "nonceStr":r.data.nonceStr,
                            "package":r.data.package,
                            "signType":r.data.signType,
                            "paySign":r.data.sign,
                        },
                        function(res){
                            var str = JSON.stringify(res);
                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                $ionicLoading.show({
                                    noBackdrop: true,
                                    template: "支付成功",
                                    duration: 1500
                                });
                                return false;
                            }else if (res.err_msg == "get_brand_wcpay_request:cancel")  {
                                $ionicLoading.show({
                                    noBackdrop: true,
                                    template: "支付取消",
                                    duration: 1500
                                });
                                return false;
                            }else{
                                //支付失败
                                $ionicLoading.show({
                                    noBackdrop: true,
                                    template: "支付失败",
                                    duration: 1500
                                });
                                return false;
                            }
                        }
                    );
                }
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                }else{
                    onBridgeReady();
                }
            } else {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: r.msg,
                    duration: 1500
                });
                return false;
            }
            //在这里请求完成以后，通知controller
            $rootScope.$broadcast('PayOK');
        })
    }

    service.checkLogin = function ($user) {
        console.log($user);
    }

    return service;
})

//用户登录
.factory('Customer', function($resource, $rootScope, $ionicLoading, ENV) {
    var ApiUrl = ENV.api,
        user,
        service = {};
    var resource = $resource(ApiUrl, {}, {
        query:{
            method: 'post',
            url: ApiUrl+'Home/UserCenter/SignIn',
            timeout: 2000
        }
    });

    service.checkLogin = function(mobile, password){
        var match_mobile = /^1[345678]\d{9}$/;
        if(!match_mobile.test(mobile)){
            $ionicLoading.show({
                noBackdrop: true,
                template: "亲爱的，请输入正确的手机号",
                duration: 1500
            });
            return false;
        }
        if(password.length < 6 || password.length > 18){
            $ionicLoading.show({
                noBackdrop: true,
                template: "亲爱的，密码长度为8~18位哦",
                duration: 1500
            });
            return false;
        }
        return true;
    }

    service.login = function(mobile, password) {
        var md5_pass = hex_md5(password);
        var sha1_pass = hex_sha1(md5_pass);
        var split_pass = sha1_pass.split("").reverse().join("");
        var pay_pass =split_pass.toUpperCase();
        return resource.query({
            mobile: mobile,
            password: pay_pass,
            no_need_sign: true
        }, function(r) {
            user = r;
            $rootScope.$broadcast('Customer.loginUpdated');
        });
    }

    service.getCurrentUser = function(){
        return user;
    }

    return service;
});